import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api, { setAuthToken } from '../api'

export const useUserStore = defineStore('user', () => {
  const user = ref(null)
  const token = ref(localStorage.getItem('token'))

  const isAuthenticated = computed(() => !!token.value)

  const login = async (credentials) => {
    const response = await api.auth.login(credentials)
    token.value = response.data.access_token
    user.value = response.data.user
    localStorage.setItem('token', token.value)
    setAuthToken(token.value)
    return response.data
  }

  const register = async (userData) => {
    const response = await api.auth.register(userData)
    return response.data
  }

  const logout = () => {
    token.value = null
    user.value = null
    localStorage.removeItem('token')
    setAuthToken(null)
  }

  const getUserInfo = async () => {
    try {
      const response = await api.users.getMe()
      user.value = response.data
      return response.data
    } catch (error) {
      if (error.response?.status === 401) {
        logout()
      }
      throw error
    }
  }

  const updateProfile = async (userData) => {
    const response = await api.users.updateProfile(user.value.id, userData)
    user.value = { ...user.value, ...response.data }
    return response.data
  }

  const changePassword = async (passwordData) => {
    const response = await api.auth.changePassword(passwordData)
    return response.data
  }

  const initializeAuth = async () => {
    if (token.value) {
      setAuthToken(token.value)
      try {
        await getUserInfo()
      } catch (error) {
        logout()
      }
    }
  }

  return {
    user,
    token,
    isAuthenticated,
    login,
    register,
    logout,
    getUserInfo,
    updateProfile,
    changePassword,
    initializeAuth
  }
})